package com.book.manager.config;


import com.book.manager.base.result.BaseResult;
import com.book.manager.base.result.Result;
import com.book.manager.exception.MyRuntimeException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author RudeCrab
 * @description 全局异常处理
 */
@RestControllerAdvice
public class ExceptionControllerAdvice {

    @ExceptionHandler(MyRuntimeException.class)
    public BaseResult<String> APIExceptionHandler(MyRuntimeException e) {
        return Result.fail(e.getMessage());
    }


    @ExceptionHandler(Exception.class)
    public BaseResult<String> MethodArgumentNotValidExceptionHandler(Exception e) {
        // 从异常对象中拿到ObjectError对象
//        ObjectError objectError = e.getMessage();
        StringBuffer messsage = new StringBuffer();
        if (e != null) {
            messsage.append(e.getClass()).append(": ").append(e.getMessage()).append("\n");
            StackTraceElement[] elements = e.getStackTrace();
            for (StackTraceElement stackTraceElement : elements) {
                messsage.append("\t").append(stackTraceElement.toString()).append("\n");
            }
        }
        String errorMsg = messsage.toString();
        // 然后提取错误提示信息进行返回
        return Result.fail(errorMsg);
    }
}
